import keys from '@/constants/storageKeys'

// debug 调试模式
const debug = false;
const debuggerToken = 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJkYXRhb2Z4IiwiaWF0IjoxNjIxMDY0MjM1LCJleHAiOjE2MjEyMzcwMzUsInVzZXJJZCI6MTJ9.z3tKRvYCJxM-6xogAkuhKtXQr4h3kjvPV-0QzLmwKNk';

//debug

/**
 * options:
 * 如果不需要登录请在options中加入noLogin:true
 */
const http = {
    request: (url, options, callback) => new Promise((resolve, reject) => {
        if (__wxConfig.envVersion === 'develop') {
            console.log(`当前请求：${url} `, options)
        }

        const token = wx.getStorageSync(keys.headerToken);
        const tokenKey = keys.tokenKey;        
        if(wx.getStorageSync(keys.SystemError)){//服务器错误            
            resolve({msg:'服务器502'})
            return ;
        }
        if (debug || (token && !options?.noLogin)) {
            if (options && options.header) {
                options.header[tokenKey] = debug ? debuggerToken : token;
            }
            else {
                if (!options.header)
                    options.header = {};
                options.header = { ...options.header, [tokenKey]: (debug ? debuggerToken : token) };

            }

        }
        if (!options?.noLogin) {        
            var isUserBind = wx.getStorageSync(keys.isUserBind);
            var inLoginPage = wx.getStorageSync(keys.inLoginPage);
            if (inLoginPage) {
                resolve({ msg:'未登录' });
                return;
            }
        }



        if(options.data){//为空和underfined的参数属性delete掉
            var data=options.data;
            for(var o in data){                
                if(data[o]==undefined||data[o]==null){
                    delete data[o];
                }
            }      
        }
        const requestTask = wx.request({
            ...options,
            url: url || options.url,
            success: res => {
                resolve(res);
            },
            fail: err => {                                      
                resolve({data:{code:-1,msg:'网络请求错误'}});
            }
        });

        // 返回RequestTask
        callback instanceof Function && callback(requestTask);
    }),
    get: (url, options = {}, callback) => http.request(url, { ...options, method: 'GET' }, callback),
    post: (url, options = {}, callback) => http.request(url, { ...options, method: 'POST' }, callback)

}
export default http;